package com.dingding.service.common.core.dao.impl;

import java.util.Date;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dao.impl.BaseDaoImpl;
import com.dingding.common.core.beans.Phonevalidate;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.service.common.core.dao.IPhonevalidateDao;

/**
 * 
 * @ClassName: Phonevalidate
 * @Description: 手机号码验证
 * @author zhaochenguang
 * @date 2015-10-10 下午01:53:59
 * @version 叮叮搭车V2.0
 */
@Component("phonevalidateDao")
public class PhonevalidateDaoImpl extends BaseDaoImpl<Phonevalidate> implements IPhonevalidateDao {

	private Logger log = Logger.getLogger(this.getClass());

	/**
	 * @Title: generatePhoneValidation
	 * @Description: 生成手机验证码
	 * @param tel 手机号
	 * @author fengshuonan
	 * @return boolean true 生成成功   false生成失败
	 * @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public Phonevalidate generatePhoneValidation(String tel) {

		Phonevalidate phonevalidate = null;

		// 判断该手机号有没有生成过验证码
		try {
			phonevalidate = super.queryCriteriaUnResult(Restrictions.eq("phoneNum", tel));
		} catch (Exception e) {
			log.error("生成手机验证码到数据库失败！PhonevalidateDaoImpl:generatePhoneValidation()", e);
		}

		// 如果没生成过验证码
		if (phonevalidate == null) {
			phonevalidate = new Phonevalidate();
			phonevalidate.setVid(ToolUtil.getUid());
			phonevalidate.setPhoneNum(tel);
			phonevalidate.setValidateCodeNumber(0);
		}

		phonevalidate.setCreateTime(new Date());
		phonevalidate.setValidateNum(ToolUtil.generateCellPhoneValNum());
		phonevalidate.setIsValid(1);
		phonevalidate.setValidateCodeNumber(0);

		try {
			super.save(phonevalidate);
		} catch (Exception e) {
			log.error("生成手机验证码到数据库失败！PhonevalidateDaoImpl:generatePhoneValidation()", e);
		}

		return phonevalidate;
	}

	/**
	 * @Title: verificationCode 
	 * @Description: 验证验证码是否输入正确 
	 * @param tellPhone 用户登录账户(手机号)
	 * @param validateNum 验证码
	 * @author YHQ
	 * @return boolean    返回类型    true:验证通过  false:验证不通过
	 * @Override
	 */
	@Transactional(readOnly = true)
	public boolean verificationCode(String tellPhone, String validateNum) {

		// 创建用于存储验证码信息的对象
		Phonevalidate phonevalidate = null;

		// 设置获取验证信息的条件
		Criterion criterion = Restrictions.and(Restrictions.eq("phoneNum", tellPhone),
				Restrictions.eq("validateNum", validateNum));

		try {
			// 根据设置条件获取验证码信息
			phonevalidate = super.queryCriteriaUnResult(criterion);
		} catch (Exception e) {
			log.error("验证验证码是否输入正确 时出现异常   类：" + this.getClass() + " verificationCode()", e);
			return false;
		}

		// 判断获取到的验证码信息是否为空，如果为空，则验证不通过
		if (phonevalidate == null) {
			return false;
		}

		return true;
	}

}
